package com.sdp.irrigation.excel.field;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.excel.context.AnalysisContext;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sdp.core.bizc.vo.BusinessContext;
import com.sdp.irrigation.cache.EqValveCache;
import com.sdp.irrigation.cache.IrrigationCleanCache;
import com.sdp.irrigation.db.irrigation_eq.service.IIrrigationEqService;
import com.sdp.irrigation.db.irrigation_eq_valve.service.IIrrigationEqValveService;
import com.sdp.irrigation.db.irrigation_pump_well.service.IIrrigationPumpWellService;
import com.sdp.irrigation.entity.IrrigationEq;
import com.sdp.irrigation.entity.IrrigationEqValve;
import com.sdp.irrigation.entity.IrrigationPumpWell;
import com.sdp.irrigation.utils.IrrigationConstants;
import com.sdp.irrigation.view.PumpWellExcelVo;
import com.sdp.right.entity.SysImportTemplateDetail;
import com.sdp.right.excel.importExcel.ImportExcelCallbackService;
import com.sdp.right.excel.importExcel.ImportExcelRowCallbackService;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;

@Service
public class PumpWellExcelCallback implements ImportExcelCallbackService, ImportExcelRowCallbackService {

	private final ThreadLocal<PumpWellExcelVo> threadLocal = ThreadLocal.withInitial(PumpWellExcelVo::new);
	
	@Autowired
	private IIrrigationPumpWellService pumpWellService;
	
	@Autowired
	private IIrrigationEqValveService eqValveService;
	
	@Autowired
	private EqValveCache eqValveCache;
	
	@Autowired
	private IIrrigationEqService eqService;
	
	@Autowired
	private IrrigationCleanCache irrigationCleanCache;
	
	@Override
	public <T> void execute(T rowData, List<T> insertList, List<T> updateList,
			List<SysImportTemplateDetail> templateDetailList, AnalysisContext context) {
		IrrigationPumpWell pumpWell = (IrrigationPumpWell) rowData;
		PumpWellExcelVo pumpWellExcelVo = threadLocal.get();
		Set<String> pumpWellNoSet = pumpWellExcelVo.getPumpWellNoSet();
		pumpWellNoSet.add(pumpWell.getPwNo());
		Set<String> eqNoSet = pumpWellExcelVo.getEqNoSet();
		if (!StringUtils.isEmpty(pumpWell.getEqNo())) {
			eqNoSet.add(pumpWell.getEqNo());
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> void executeBatch(List<T> rowDataList, List<T> insertList, List<T> updateList,
			List<SysImportTemplateDetail> templateDetailList, AnalysisContext context) {
		CopyOptions options = CopyOptions.create()
                .setIgnoreNullValue(true);
		Set<String> pumpWellNoSet = threadLocal.get().getPumpWellNoSet();
		QueryWrapper<IrrigationPumpWell> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().in(IrrigationPumpWell::getPwNo, pumpWellNoSet);
		List<IrrigationPumpWell> pumpWellList = pumpWellService.list(queryWrapper);
		Map<String, IrrigationPumpWell> pumpWellMap = new HashMap<>();
		for (IrrigationPumpWell pumpWell : pumpWellList) {
			pumpWellMap.put(pumpWell.getPwNo(), pumpWell);
		}
		
		Set<String> eqNoSet = threadLocal.get().getEqNoSet();
		Map<String, IrrigationEq> eqMap = new HashMap<>();
		if (eqNoSet.size() > 0) {
			QueryWrapper<IrrigationEq> eqQueryWrapper = new QueryWrapper<>();
			eqQueryWrapper.lambda().in(IrrigationEq::getEqNo, eqNoSet);
			List<IrrigationEq> eqList = eqService.list(eqQueryWrapper);
			
			for (IrrigationEq eq : eqList) {
				eqMap.put(eq.getEqNo(), eq);
			}
		}
		
		List<IrrigationEqValve> eqValveList = new ArrayList<>();
		
		//先删除机井绑定设备对应的阀门
		QueryWrapper<IrrigationEqValve> eqValveQueryWrapper = new QueryWrapper<>();
		eqValveQueryWrapper.lambda().in(IrrigationEqValve::getEqNo, eqNoSet);
		eqValveService.remove(eqValveQueryWrapper);
		
		for (Object obj : rowDataList) {
			IrrigationPumpWell row = (IrrigationPumpWell) obj;
			//设置机井中的封面图
			if (eqMap.containsKey(row.getEqNo())) {
				row.setEqCoverimg(eqMap.get(row.getEqNo()).getEqCoverimg());
			}
			
			if (pumpWellMap.containsKey(row.getPwNo())) {
				BeanUtil.copyProperties(row, pumpWellMap.get(row.getPwNo()), options);
				updateList.add((T) pumpWellMap.get(row.getPwNo()));
			} else {
				row.setEqRepairStatus(IrrigationConstants.否.getCode());
				row.setCreateTime(LocalDateTime.now());
				row.setUpdateTime(row.getCreateTime());
				insertList.add((T) row);
			}
			//添加机井对应设备的阀门数据
			if (!StringUtils.isEmpty(row.getValveNum()) && !StringUtils.isEmpty(row.getEqNo())) {
				for (int i = 0; i < row.getValveNum(); i++) {
					IrrigationEqValve eqValve = new IrrigationEqValve();
					eqValve.setEqNo(row.getEqNo());
					eqValve.setSerialNo(i + 1);
					eqValve.setSwitchStatus(IrrigationConstants.否.getCode());
					//eqValve.setValveNo(valveNo);
					eqValve.setValveName(eqValve.getSerialNo() + "");
					eqValve.setCreateTime(LocalDateTime.now());
					eqValve.setUpdateTime(LocalDateTime.now());
					eqValveList.add(eqValve);
				}
				
				//删除缓存
				eqValveCache.deleteEqValveCache(row.getEqNo());
				
				//插入阀门信息
				if (eqValveList.size() >= 1000) {
					eqValveService.saveBatch(eqValveList);
					eqValveList.clear();
				}
			}
		}
		
		if (eqValveList.size() > 0) {
			eqValveService.saveBatch(eqValveList);
		}
		
		//清理
		eqValveList.clear();
		eqValveList = null;
		pumpWellList.clear();
		pumpWellList = null;
		pumpWellMap.clear();
		pumpWellMap = null;
		eqMap.clear();
		eqMap = null;
		pumpWellNoSet.clear();
		eqNoSet.clear();
	}

	@Override
	public BusinessContext execute(HttpServletRequest request, HttpServletResponse response) {
//		threadLocal.get().getEqNoSet().clear();
//		threadLocal.get().getPumpWellNoSet().clear();
		BusinessContext businessContext = new BusinessContext();
		irrigationCleanCache.cleanPumpWell();
		return businessContext;
	}

}
